#include "main_widget.h"

Main_Widget::Main_Widget(QWidget* parent) : QWidget(parent) , file(false) {
	ui.setupUi(this);
	connect(ui.render_button, SIGNAL(clicked()), this, SLOT(render()));

}

Main_Widget::~Main_Widget(void) {
	delete input;
	delete raytracer;
	delete grid;
	delete scene;
}

void Main_Widget::file_opened(QString _filename) {
	input = new Input(_filename);
	input->parse();
	raytracer = input->get_raytracer();
	grid = input->get_grid();
	scene = input->get_scene();
	file = true;
	input->save();
}

void Main_Widget::file_closed(void) {
	if(file) {
		hide();
		(ui.image)->clear();
		delete input;
		delete raytracer;
		file = false;
	}
}

void Main_Widget::render(void) {
	if(raytracer != NULL && scene != NULL && grid != NULL) {
		Output* file = new Qtimage(grid->get_height(),grid->get_width());
		raytracer->set_output(file);
		QTime timer;
		int rendering_time;
		
		timer.start();
		raytracer->render();
		rendering_time = timer.elapsed();
		file = raytracer->get_output();
		
		QImage* image = ((Qtimage*) file)->get_QImage();
		
		(ui.image)->setPixmap(QPixmap::fromImage(*image));
		(ui.image)->adjustSize();
		
		emit statusbar_message(tr("%1 milliseconds to render.").arg(rendering_time));
	}
	else {
		QMessageBox::information(this, tr("Sirat"),tr("Cannot render."));
	}
}
